package com.qkl.xiatang.app.service.impl;

import com.google.gson.Gson;
import com.qkl.xiatang.app.dto.mqtt.MqttReceiveDTO;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MqttCallbackImpl implements MqttCallback {

    @Autowired
    private MqttDeviceService mqttDeviceService;

    private Gson gson = new Gson();

    @Override
    public void connectionLost(Throwable throwable) {

    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        String dataJson = new String(mqttMessage.getPayload());
        log.info("接收消息主题: topic={},内容 content={}",topic,dataJson);

        MqttReceiveDTO receiveData = gson.fromJson(dataJson,MqttReceiveDTO.class);
        mqttDeviceService.addMqttReceiveData(receiveData);

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
